<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="[]">
            <template #refreshAppend>
                <div>
                    <el-input v-model="filterParams.cash_out_no" class="ml-3 w-40" placeholder="订单号" clearable></el-input>
                    <el-input v-model="filterParams.keyword" class="ml-3 w-40" placeholder="用户名称" clearable></el-input>
                    <el-date-picker
                        v-model="filterParams.start_time"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        class="ml-2 w-52"
                    />
                    <span class="ml-2">~</span>
                    <el-date-picker
                        v-model="filterParams.end_time"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        class="ml-2 w-52"
                    />
                    <el-button class="ml-3" @click="handleSearch('reset')">
                        <Icon name="fa fa-refresh" class="text-current text-sm mr-1"></Icon>重置
                    </el-button>
                    <el-button type="primary" @click="handleSearch('search')">
                        <Icon name="fa fa-search" class="text-white text-sm mr-1"></Icon>查询
                    </el-button>
                </div>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <div class="bg-white mt-2 p-3">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
                <el-tab-pane :label="`待审核(${tabNums.onShelfTotal})`" name="first"></el-tab-pane>
                <el-tab-pane :label="`已完成(${tabNums.soldOutTotal})`" name="second"></el-tab-pane>
                <el-tab-pane :label="`已取消(${tabNums.offShelfTotal})`" name="third"></el-tab-pane>
            </el-tabs>
            <Table ref="tableRef">
                <template #action>
                    <el-table-column :label="filterParams.status == 1 ? '操作' : '操作人'">
                        <template #default="scope">
                            <div style="cursor: pointer; display: flex" v-if="filterParams.status == 1">
                                <div>
                                    <span @click="openDialog(scope.row.id)" style="color: red">拒绝转账</span>
                                </div>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <el-popconfirm
                                    width="220"
                                    confirm-button-text="确认"
                                    cancel-button-text="取消"
                                    :title="`确定给${scope.row.transfer_account}账号转账?`"
                                    @confirm="agree(scope.row.id)"
                                >
                                    <template #reference>
                                        <div>
                                            <span style="color: #4b9cfb">支付宝转账</span>
                                        </div>
                                    </template>
                                </el-popconfirm>
                            </div>
                            <div v-else>
                                {{ scope.row.admin.nickname }}
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template #refuse_reason v-if="activeName=='third'">
                    <el-table-column label="拒绝理由">
                        <template #default="scope">
                            <span>{{ scope.row.refuse_reason }}</span>
                        </template>
                    </el-table-column>
                </template>
                <template #audit_time v-if="activeName!='first'">
                    <el-table-column label="操作时间" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.audit_time }}</span>
                        </template>
                    </el-table-column>
                </template>
                <template #status >
                    <el-table-column label="订单状态" align="center">
                        <template #default="scope">
                            <span v-if="activeName=='first'" style="color: #e6a23c">{{ scope.row.status_name }}</span>
                            <span v-if="activeName=='second'" style="color: #67c23a">{{ scope.row.status_name }}</span>
                            <span v-if="activeName=='third'" style="color: #f56c6c">{{ scope.row.status_name }}</span>
                        </template>
                    </el-table-column>
                </template>
            </Table>
        </div>
        <!-- 填写拒绝理由 -->
        <el-dialog v-model="dialogFormVisible" title="拒绝退款" width="500">
            <el-form>
                <el-form-item label="拒绝理由">
                    <el-input v-model="refuse_reason" placeholder="请输入拒绝理由" style="width: 240px" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="(dialogFormVisible = false), (refuse_reason = '')">取消</el-button>
                    <el-button @click="refuse" type="primary"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { isEmpty, parseInt } from 'lodash-es'
import { ref, provide, reactive, watch, onMounted } from 'vue'
import baTableClass from '/@/utils/baTable'
import { url } from '/@/api/backend/user/moneyLog'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { baTableApi } from '/@/api/common'
import { useRoute } from 'vue-router'
import { add } from '/@/api/backend/user/moneyLog'
import { useI18n } from 'vue-i18n'
import createAxios from '/@/utils/axios'
import { ElMessage } from 'element-plus'
defineOptions({
    name: 'user/moneyLog',
})

let filterParams: any = ref({
    status: 1, // 0为未上架  1为上架中
    scock: null, // 1=已售罄
    category: null, // 分类ID
    ean: null, //编号
    money_price_min: null, // 起始金额
    money_price_max: null, // 结束金额
    title: null, // 标题
    order_by: null, // 1=商品金额降序 2=商品金额升序 3=创建时间降序 4= 创建时间升序
    brand_id: null, //品牌ID
})
// 同意转账
const agree = async (rowId: any) => {
    await createAxios({
        url: '/admin/member.CashOut/audit',
        method: 'post',
        data: { id: rowId, action: 'agree' },
    }).then((res) => {
        handleClick()
        ElMessage({ type: 'success', message: '操作成功' })
        console.log('res', res)
    })
}
// 拒绝转账
const dialogFormVisible = ref(false)
const refuse_reason = ref('')
const orderId = ref(null)
const openDialog = (rowId: any) => {
    dialogFormVisible.value = true
    orderId.value = rowId
}
const refuse = async () => {
    if (refuse_reason.value) {
        await createAxios({
            url: '/admin/member.CashOut/audit',
            method: 'post',
            data: { id: orderId.value, action: 'refuse', refuse_reason: refuse_reason.value },
        }).then((res) => {
            dialogFormVisible.value = false
            refuse_reason.value = ''
            handleClick()
            ElMessage({ type: 'success', message: '操作成功' })
        })
    } else {
        ElMessage({ type: 'warning', message: '请输入拒绝理由' })
    }
}
// 更新数据
let tabNums = ref({
    onShelfTotal: 0,
    offShelfTotal: 0,
    soldOutTotal: 0,
})
const handleClick = () => {
    // filterParams.value.stock = null
    filterParams.value.status = null
    if (activeName.value === 'first') {
        filterParams.value.status = 1
    } else if (activeName.value === 'second') {
        filterParams.value.status = 2
    } else if (activeName.value === 'third') {
        filterParams.value.status = 3
    }
    filter.value!.status = filterParams.value.status
    filter.value!.stock = filterParams.value.stock
    baTable.getIndex()?.then(() => {
        tabNums.value = {
            onShelfTotal: baTable.table.allData!.status_wait_audit,
            offShelfTotal: baTable.table.allData!.status_transfered,
            soldOutTotal: baTable.table.allData!.status_wait_transfer,
        }
    })
}

const { t } = useI18n()
let activeName: any = ref('first') //tab切换绑定值
const tableRef = ref()
const route = useRoute()
const defalutUser = (route.query.user_id ?? '') as string
const state: {
    userInfo: anyObj
} = reactive({
    userInfo: {},
})
// 搜索操作
const handleSearch = (type: string) => {
    if (type === 'reset') {
        filterParams.value = {
            cash_out_no: '', // 订单号
            keyword: '', //物流单号
            start_time: '', // 开始时间
            end_time: '', // 结束时间
            status: '', //订单状态 1待处理 2已完成 3已取消
        }
    }
    //赋值给baTable的filter对象
    filter.value!.cash_out_no = filterParams.value.cash_out_no
    filter.value!.keyword = filterParams.value.keyword
    filter.value!.start_time = filterParams.value.start_time
    filter.value!.end_time = filterParams.value.end_time
    filter.value!.status = filterParams.value.status
    baTable.getIndex()?.then(() => {})
}
const baTable = new baTableClass(
    new baTableApi('/admin/member.CashOut/lists/'),
    {
        pk: 'id',
        filter: {
            status: 1,
        },
        column: [
            // { type: 'selection', align: 'center', operator: false },
            { label: '提现订单id', prop: 'cash_out_no', align: 'center', operator: '=', operatorPlaceholder: t('Id'), width: 150 },
            { label: t('user.moneyLog.User ID'), prop: 'member_id', align: 'center', width: 70 },
            {
                label: t('user.moneyLog.User name'),
                prop: 'member.nickname',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
            },

            { label: '提现金额', prop: 'money', align: 'center', operator: 'RANGE' },
            { label: t('user.moneyLog.Before change'), prop: 'apply_money', align: 'center', operator: 'RANGE' },
            { label: t('user.moneyLog.After change'), prop: 'service_money', align: 'center', operator: 'RANGE' },
            {
                label: '支付宝账号',
                prop: 'transfer_account',
                align: 'center',
                operator: 'LIKE',
                operatorPlaceholder: t('Fuzzy query'),
                showOverflowTooltip: true,
            },
            { label: t('Create time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', width: 160 },
            { label: '操作时间', prop: 'audit_time', align: 'center',  operator: 'RANGE',slotName: 'audit_time', render: 'slot' },
            { label: '状态', prop: 'status_name', align: 'center', operator: 'RANGE',render:'slot',slotName:'status' },
            { label: '拒绝理由', prop: 'refuse_reason', align: 'center', operator: 'RANGE', slotName: 'refuse_reason', render: 'slot' },
            { label: '操作', prop: 'action', slotName: 'action', render: 'slot' },
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {
            user_id: defalutUser,
            memo: '',
        },
    },
    {},
    {
        onSubmit: () => {
            getUserInfo(baTable.comSearch.form.user_id)
        },
    }
)

baTable.mount()
baTable.getIndex()

provide('baTable', baTable)
let filter = ref(baTable.table.filter)

const getUserInfo = (userId: string) => {
    if (userId && parseInt(userId) > 0) {
        add(userId).then((res) => {
            state.userInfo = res.data.user
        })
    } else {
        state.userInfo = {}
    }
}

getUserInfo(baTable.comSearch.form.user_id)

watch(
    () => baTable.comSearch.form.user_id,
    (newVal) => {
        baTable.form.defaultItems!.user_id = newVal
        getUserInfo(newVal)
    }
)
onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
        tabNums.value = {
            onShelfTotal: baTable.table.allData!.status_wait_audit,
            offShelfTotal: baTable.table.allData!.status_transfered,
            soldOutTotal: baTable.table.allData!.status_wait_transfer,
        }
    })
})
</script>

<style scoped lang="scss"></style>
